package com.redlight.base;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by chao on 2019/1/9.
 */
public class JsonUtil extends JSONUtils {
    private static SerializeConfig mapping = new SerializeConfig();
    private static SerializerFeature[] features;

    public JsonUtil() {
    }

    public static String toJson(Object o) {
        return JSON.toJSONString(o, mapping, features);
    }

    public static String toJson(Object o, String _dateFormat) {
        mapping.put(Date.class, new SimpleDateFormatSerializer(_dateFormat));
        return JSON.toJSONString(o, mapping, features);
    }

    public static Map<String, Object> toMap(String json) {
        Map<String, Object> map = (Map)JSON.parseObject(json, Map.class);
        Iterator var2 = map.entrySet().iterator();

        while(var2.hasNext()) {
            Map.Entry<String, Object> m = (Map.Entry)var2.next();
            Object val = m.getValue();
            if(val instanceof JSONObject) {
                Map<String, Object> mp = toMap(((JSONObject)val).toJSONString());
                map.put(m.getKey(), mp);
            }
        }

        return map;
    }

    public static <T> T toBean(String json, Class clazz) {
        return JSON.parseObject(json, (Class<T>) clazz);
    }



    static {
        features = new SerializerFeature[]{SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect};
        mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
    }
}
